#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/progress.hpp>
#include "DatabaseManager.h"
#include "../Config.h"

void DatabaseManager::loadDatabase()
{
  if (!boost::filesystem::exists(PATH_DATAS))
    return;
  if (boost::filesystem::is_directory(PATH_DATAS) )
    {
      boost::filesystem::directory_iterator end_iter;
      for (boost::filesystem::directory_iterator dir_itr(PATH_DATAS);
	   dir_itr != end_iter;
	   ++dir_itr)
	{
	  try
	    {
	      if (boost::filesystem::is_regular_file(dir_itr->status()))
		{
		  std::cout << "Loading contact " << dir_itr->path().filename() << "...\n";
		  std::string gpath = std::string(PATH_DATAS);
		  gpath += dir_itr->path().filename();
		  this->loadOneContact(gpath);
		}
	    }
	  catch (const std::exception & ex)
	    {
	      std::cerr << "[Error] " << dir_itr->path().filename() << " " << ex.what() << std::endl;
	    }
	}
    }
}

void DatabaseManager::loadOneContact(const std::string &filename)
{
  try
    {
      Client *clt = Client::load(filename);
      this->_clients[clt->getLogin()] = clt;
      clt->setStatus(Client::offline);
    }
  catch (const std::exception & ex)
    {
      std::cerr << "[Error] " << "Cannot load client " << filename << std::endl;
    }
}

bool DatabaseManager::clientExist(const std::string &login)
{
  return this->_clients.count(login);
}

Client *DatabaseManager::getClientByLogin(const std::string &login)
{
  if (this->clientExist(login))
    return this->_clients[login];
  return NULL;
}

bool DatabaseManager::loginMatchPass(const std::string &login, const std::string &pass)
{
  Client *clt = this->getClientByLogin(login);
  return clt && clt->getPass() == pass;
}

